import { Form, FormInstance, Modal, TreeSelect, message } from 'antd';
import React, { useEffect, useRef, useState } from 'react';

import type { TenantAddItem } from '../data.d';
import { ProForm, ProFormSelect, ProFormText } from '@ant-design/pro-components';
import { getTenantRoleList } from '@/pages/Auth/AuthRole/service';
import { queryAdminListByPosition, queryPositionByDep } from '@/pages/user/Admin/service';
import { queryDepartment } from '@/pages/user/Department/service';

interface AddFormProps {
  onSubmit: (values: TenantAddItem) => Promise<void>;
  onCancel: (flag?: boolean) => void;
  modalVisible: boolean;
}

const AddForm: React.FC<AddFormProps> = (props) => {

  const {
    onSubmit: handleAdd,
    onCancel: handleAddModalVisible,
    modalVisible: addModalVisible,
  } = props;

  const formRef = useRef<FormInstance>();

  const [treeDate, setTreeDate] = useState<any[]>([]);
  const [positionData, setPositionData] = useState<any[]>();
  const [owningAccount, setOwningAccount] = useState<any[]>();
  const [oneTreeDisplay, setOneTreeDisplay] = useState(false);
  const [twoTreeDisplay, setTwoTreeDisplay] = useState(true);
  const [selectDisplay, setSelectDisplay] = useState(true);

  function convertData(data: { id: any; name: any; next_level: string | any[] }) {
    const node = {
      value: data.id,
      title: data.name,
      children: [] as any,
    };
    if (data.next_level && data.next_level.length > 0) {
      for (let i = 0; i < data.next_level.length; i++) {
        const child = convertData(data.next_level[i]);
        node.children.push(child);
      }
    }
    return node;
  }

  useEffect(() => {
    queryDepartment().then((res) => {
      if (res && res.code == 0) {
        const data = res?.data;
        const convert = [];
        if (data && data.length > 0) {
          for (let i = 0; i < data.length; i++) {
            convert.push(convertData(data[i]));
          }
          setTreeDate(convert);
        }
      }
    });
  }, [])


  return (
    <Modal
      title="添加客户"
      open={addModalVisible}
      width={550}
      footer={null}
      centered
      onCancel={() => handleAddModalVisible(false)}
      afterClose={() => handleAddModalVisible(false)}
    >

      <ProForm<TenantAddItem>
        onFinish={(values) => {
          return handleAdd(values)
        }}
        formRef={formRef}
        layout="vertical"
      >

        <ProFormText
          width={'xl'}
          name="name"
          label="客户名称"
          placeholder="请输入"
          rules={[{ required: true, message: '请输入客户名称' }]}
        />

        <ProFormText
          width={'xl'}
          name="push_url"
          label="推送地址"
          placeholder="请输入"
          rules={[{ required: true, message: '请输入推送地址' }]}
        />

        <ProFormText
          width={'xl'}
          name="mobile"
          label="联系方式"
          placeholder="请输入"
          rules={[{ required: true, message: '请输入联系方式' }]}
        />

        <ProFormText
          width={'xl'}
          name="mail"
          label="邮箱"
          placeholder="请输入"
          rules={[{ required: true, message: '请输入邮箱' }]}
        />

        <ProFormSelect
          label={'角色'}
          showSearch
          name="role_id"
          params={{ page: 1, pageSize: 10 }}
          request={async (_params, _props) => {
            const res: any = await getTenantRoleList();
            if (res)
              return res.data.map((item: { id: any; name: any }, _index: any) => {
                return {
                  value: item.id,
                  label: item.name,
                };
              });
          }}
          rules={[{ required: true, message: '请选择角色' }]}
          placeholder="请选择角色"
        />

        <Form.Item
          name="department_id"
          label="部门选择"
        >
          <TreeSelect
            disabled={oneTreeDisplay}
            showSearch
            style={{ width: '100%' }}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            placeholder="请选择部门"
            allowClear
            autoClearSearchValue
            treeDefaultExpandAll
            onChange={(newValue, _labelList) => {
              if (newValue) {
                queryPositionByDep(newValue).then((res) => {
                  if (res && res.code == 0 && res.data.length > 0) {
                    const data = res?.data;
                    const convert = [];
                    for (let i = 0; i < data.length; i++) {
                      convert.push(convertData(data[i]));
                    }
                    setPositionData(convert);
                    setOneTreeDisplay(true);
                    setTwoTreeDisplay(false);
                  }
                  else {
                    message.error("暂无可选职位")
                  }
                });
              }
            }}
            treeData={treeDate}
          />
        </Form.Item>

        <Form.Item
          name="position_id"
          label="职位选择"
        >
          <TreeSelect
            disabled={twoTreeDisplay}
            autoClearSearchValue
            showSearch
            onChange={(newValue) => {
              queryAdminListByPosition(newValue).then((res) => {
                if (res && res.code == 0 && res.data.length > 0) {
                  setOwningAccount(
                    res.data?.map((item: { id: any; name: any }) => {
                      return {
                        value: item.id,
                        label: item.name,
                      };
                    }),
                  );
                  setTwoTreeDisplay(true);
                  setSelectDisplay(false);
                } else {
                  message.error('该职位暂无管理员');
                }
              });
            }}
            style={{ width: '100%' }}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            placeholder="请选择职位"
            allowClear
            treeDefaultExpandAll
            treeData={positionData}
          />
        </Form.Item>

        <ProFormSelect
          options={owningAccount}
          label={'所属管理员'}
          disabled={selectDisplay}
          name="belong"
          placeholder="选择所属管理员（请先选择职位）"
        />
      </ProForm>

    </Modal >
  );
};
export default AddForm;
